package com.sgb.kjwl.view.ui.activity.pick;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPickExpertEditBinding;
import com.sgb.kjwl.viewmodel.pick.PickExpertEditModel;
import com.sgb.zhaocai.entity.PickExpertDetailEntity;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.selection.CommonPopEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 专家库-新增（编辑）页面
 */
public class PickExpertEditActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityPickExpertEditBinding mBinding;
    private PickExpertEditModel mModel;
    PickExpertDetailEntity bean = new PickExpertDetailEntity();

    // 地址一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 地址二级联动数据
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 地址三级联动数据
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    private List<PickSelectEntity> tvCategoryData = new ArrayList<>();
    private List<PickSelectEntity> jobTitleData = new ArrayList<>();
    private List<PickSelectEntity> genderData = new ArrayList<>();
    private List<CommonPopEntity> professionalData = new ArrayList<>();
    private List<List<CommonPopEntity>> typeData = new ArrayList<>();
    private String professionalName;
    private String typeName = "";
    private Calendar selectedDate;
    private PickExpertDetailEntity.Majors majors = new PickExpertDetailEntity.Majors();
    private String no;

    public static void start(Context context, String no) {
        Intent intent = new Intent(context, PickExpertEditActivity.class);
        intent.putExtra("no", no);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_pick_expert_edit);
        mModel = new ViewModelProvider(this).get(PickExpertEditModel.class);
        ViewOnClick();
    }

    @Override
    protected void init() {
        super.init();
        no = getIntent().getStringExtra("no");
        if (!TextUtils.isEmpty(no)) {
            mModel.detail(this, no);
        }

        if (!TextUtils.isEmpty(no)) {
            mBinding.includeTitle.titleView.setText("编辑");
        }else{
            mBinding.includeTitle.titleView.setText("新增");
        }

        genderData.add(new PickSelectEntity("01", "男"));
        genderData.add(new PickSelectEntity("02", "女"));
        mModel.getCertificateList(this);
        mModel.getAllMajorCategoryList(this);
    }

    /**
     * 详情返回方法
     */
    public void setDetailsData(PickExpertDetailEntity pickExpertDetailEntity) {
        bean = pickExpertDetailEntity;
        mBinding.tvName.setContent(pickExpertDetailEntity.getFullName());
        if ("01".equals(pickExpertDetailEntity.getGenderType())) {
            mBinding.tvGender.setContent("男");
        } else if ("02".equals(pickExpertDetailEntity.getGenderType())) {
            mBinding.tvGender.setContent("女");
        } else {
            mBinding.tvGender.setContent("");
        }
        mBinding.tvPhone.setContent(pickExpertDetailEntity.getUserName());
        mBinding.tvJobTitle.setContent(pickExpertDetailEntity.getProfessionName());
        mBinding.tvCategory.setContent(pickExpertDetailEntity.getCategoryTypeName());
        mBinding.tvUnit.setContent(pickExpertDetailEntity.getComName());
        mBinding.tvPost.setContent(pickExpertDetailEntity.getJob());
        mBinding.tvAddress.setContent(pickExpertDetailEntity.getAddressName());
        mBinding.tvSocialSecurityNumber.setContent(pickExpertDetailEntity.getIdentityCard());
        mBinding.tvRemark.setEditContent(pickExpertDetailEntity.getMark());

        if (pickExpertDetailEntity.getCustomArray() != null && pickExpertDetailEntity.getCustomArray().size() > 0) {
            mBinding.expertNew.setData(pickExpertDetailEntity.getCustomArray());
        }

        if (pickExpertDetailEntity.getMajors() != null && pickExpertDetailEntity.getMajors().size() > 0) {
            majors = pickExpertDetailEntity.getMajors().get(0);
            mBinding.tvProfessional.setContent(majors.getMajorName());
            mBinding.tvStartYear.setContent(majors.getStartYear());
            mBinding.evaluationProfessional.setFirstFinish(majors,false);
            if(pickExpertDetailEntity.getMajors().size() > 1){
                pickExpertDetailEntity.getMajors().remove(0);
                mBinding.evaluationProfessional.setData(pickExpertDetailEntity.getMajors());
            }
        }

        if (pickExpertDetailEntity.getQualifications() != null && pickExpertDetailEntity.getQualifications().size() > 0) {
            mBinding.practisingCertificate.setData(pickExpertDetailEntity.getQualifications());
        }

    }

    /**
     * 初始化点击事件
     */
    private void ViewOnClick() {

        mBinding.includeTitle.ivBack.setOnClickListener(this::onClick);
        mBinding.delete.setOnClickListener(this::onClick);
        mBinding.tvSubmit.setOnClickListener(this::onClick);
        mBinding.tvGender.setOnWholeItemClickListener(this::OnWholeItemClick);
        mBinding.tvJobTitle.setOnWholeItemClickListener(this::OnWholeItemClick);
        mBinding.tvCategory.setOnWholeItemClickListener(this::OnWholeItemClick);
        mBinding.tvAddress.setOnWholeItemClickListener(this::OnWholeItemClick);
        mBinding.tvProfessional.setOnWholeItemClickListener(this::OnWholeItemClick);
        mBinding.tvStartYear.setOnWholeItemClickListener(this::OnWholeItemClick);

        mBinding.tvPhone.setInfilterType(ItemInputTextView.TYPE_PHONE);
        mBinding.tvSocialSecurityNumber.setInfilterType(ItemInputTextView.TYPE_INDO);
        mBinding.tvStartYear.setDeliverLineVG(false);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete:
                List<PickExpertDetailEntity.Majors> majorsList = mBinding.evaluationProfessional.getCustomFieldViewData();
                if (majorsList == null || majorsList.size() == 0) {
                    ToastUtil.show(this, "至少请填写一条评标专业！");
                } else {
                    mBinding.evaluationProfessionalFirst.setVisibility(View.GONE);
                    majors = null;
                    mBinding.evaluationProfessional.setFirstFinish(null, true);
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_submit:
                submitData();
                break;
        }

    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.tv_gender:
                showListPop("性别", mBinding.tvGender, genderData);
                break;
            case R.id.tv_job_title:
                if (jobTitleData.size() == 0) {
                    mModel.getProfessionList(this);
                } else {
                    showListPop("职称", mBinding.tvJobTitle, jobTitleData);
                }
                break;
            case R.id.tv_category:
                if (tvCategoryData.size() == 0) {
                    mModel.getCategoryTypeList(this);
                } else {
                    showListPop("所属专业类别", mBinding.tvCategory, tvCategoryData);
                }
                break;
            case R.id.tv_professional:
                if (professionalData.size() == 0) {
                    mModel.getAllMajorCategoryList(this);
                }
                showProfessionalTypePop();
                break;
            case R.id.tv_start_year:
                showTimePop();
                break;
            case R.id.tv_address:
                if (addressEntityList == null) {
                    mModel.getAddressModel(this);
                } else {
                    showCityPop();
                }
                break;
        }

    }

    /**
     * 专家库发布所属类别列表
     */
    public void setCategoryType(List<PickSelectEntity> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        this.tvCategoryData = data;
        showListPop("所属专业类别", mBinding.tvCategory, tvCategoryData);
    }

    /**
     * 专家库发布专家职称列表
     */
    public void setProfessionList(List<PickSelectEntity> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        this.jobTitleData = data;
        showListPop("职称", mBinding.tvJobTitle, jobTitleData);
    }

    /**
     * 专家库发布评标专业列表
     */
    public void setAllMajorCategoryList(List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        for (CommonPopEntity commonPopEntity : data) {
            professionalData.add(new CommonPopEntity(commonPopEntity.getNo(), commonPopEntity.getTypeName()));
            List<CommonPopEntity> commonPopEntityList = commonPopEntity.getChildren();
            typeData.add(commonPopEntityList);
        }

        mBinding.evaluationProfessional.setCertificateData(professionalData, typeData);
    }

    /**
     * 专家库发布执业资格列表
     */
    public void setCertificateList(List<PickSelectEntity> data) {
        mBinding.practisingCertificate.setCertificateData(data);
    }

    /**
     * 地址信息
     */
    public void setAddressList(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        initJsonData();
        showCityPop();
    }

    //组装省市区数据信息
    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }

    public void showCityPop() {
        List<String> strings = new ArrayList<>();
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
                bean.setArea("");
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                bean.setArea(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String provinceName = addressEntityList.get(options1).getName();
            String cityName = opt2.get(options1).get(options2).getName();
            if (!TextUtils.isEmpty(cityName)) {
                if (!TextUtils.isEmpty(areaName)) {
                    mBinding.tvAddress.setContent(provinceName + "/" + cityName + "/" + areaName);
                } else {
                    mBinding.tvAddress.setContent(provinceName + "/" + cityName);
                }
            } else {
                mBinding.tvAddress.setContent(provinceName);
            }
            strings.add(provinceName);
            strings.add(cityName);
            strings.add(areaName);
            bean.setProvince(addressEntityList.get(options1).getNo());
            bean.setCity(opt2.get(options1).get(options2).getNo());
            bean.setAddress(strings);
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD")).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();

    }

    /**
     * 时间
     */
    private void showTimePop() {
        selectedDate = Calendar.getInstance();
        selectedDate.add(Calendar.DAY_OF_MONTH, 0);
        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String format = sdf.format(date);
            mBinding.tvStartYear.setContent(format);
            majors.setStartYear(format);
            mBinding.evaluationProfessional.setFirstFinish(majors,false);
        }).setType(new boolean[]{true, false, false, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("从事该专业起始年份")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setRangDate(null, selectedDate)
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        timePicker.show();
    }

    //评标专业
    private void showProfessionalTypePop() {
        List<String> string = new ArrayList<>();
        if (professionalData.size() == 0) return;
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            professionalName = professionalData.get(options1).getTypeName();
            string.add(professionalData.get(options1).getNo());
            if (typeData.size() == 0 || null == typeData.get(options1) || typeData.get(options1).size() == 0 || typeData.get(options1).get(options2) == null) {

            } else {
                typeName = typeData.get(options1).get(options2).getTypeName();
                string.add(typeData.get(options1).get(options2).getNo());
            }
            if (!TextUtils.isEmpty(typeName)) {
                mBinding.tvProfessional.setContent(professionalName + "/" + typeName);
                majors.setMajorName(professionalName + "/" + typeName);
            } else {
                mBinding.tvProfessional.setContent(professionalName);
                majors.setMajorName(professionalName);
            }
            majors.setMajor(string);
            mBinding.evaluationProfessional.setFirstFinish(majors,false);
        }).setCancelColor(Color.parseColor("#666666"))
                .setSubCalSize(15)
                .setTitleText("选择评标专业")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitColor(Color.parseColor("#5792FD")).build();
        businessOption.setPicker(professionalData, typeData);
        businessOption.setSelectOptions(0, 0);
        businessOption.show();
    }

    /**
     * 一级选择弹窗
     */
    private void showListPop(String titles, View inputTextView, List<PickSelectEntity> data) {
        if (data != null && data.size() > 0) {
            OptionsPickerView<PickSelectEntity> mCustomerOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    if (inputTextView.getId() == R.id.tv_gender) {//性别
                        mBinding.tvGender.setContent(data.get(options1).getProjectscale());
                        bean.setGenderType(data.get(options1).getNo());
                    }
                    if (inputTextView.getId() == R.id.tv_job_title) {//职称
                        mBinding.tvJobTitle.setContent(data.get(options1).getProjectscale());
                        bean.setProfession(data.get(options1).getNo());
                        bean.setProfessionName(data.get(options1).getProjectscale());
                    }
                    if (inputTextView.getId() == R.id.tv_category) {//所属类别
                        mBinding.tvCategory.setContent(data.get(options1).getProjectscale());
                        bean.setCategoryTypeName(data.get(options1).getProjectscale());
                        bean.setCategoryType(data.get(options1).getNo());
                    }
                }
            }).setCancelColor(Color.parseColor("#666666"))
                    .setSubCalSize(15)
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                    .setSubmitColor(Color.parseColor("#5792FD")).build();
            mCustomerOptions.setTitleText(titles);
            mCustomerOptions.setPicker(data);
            mCustomerOptions.setSelectOptions(0);
            mCustomerOptions.show();
        }
    }

    //提交数据
    private void submitData() {
        if (TextUtils.isEmpty(mBinding.tvName.getContent())) {
            MToast.showToast(this, "请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(mBinding.tvPhone.getContent())) {
            MToast.showToast(this, "请输入手机号");
            return;
        }
        if (!CheckUtils.isMobileNum_new(mBinding.tvPhone.getContent())) {
            MToast.showToast(this, "请输入正确的手机号");
            return;
        }
        if (TextUtils.isEmpty(mBinding.tvJobTitle.getContent())) {
            MToast.showToast(this, "请选择职称");
            return;
        }
        if (TextUtils.isEmpty(mBinding.tvCategory.getContent())) {
            MToast.showToast(this, "请选择所属类别");
            return;
        }
        if (TextUtils.isEmpty(mBinding.tvAddress.getContent())) {
            MToast.showToast(this, "工作地区");
            return;
        }
        if (!TextUtils.isEmpty(mBinding.tvSocialSecurityNumber.getContent())) {
            if (!CheckUtils.isIDNumber(mBinding.tvSocialSecurityNumber.getContent())) {
                MToast.showToast(this, "请输入正确的身份证号");
                return;
            }
        }
        if (TextUtils.isEmpty(mBinding.tvProfessional.getContent()) || TextUtils.isEmpty(mBinding.tvStartYear.getContent())) {
            MToast.showToast(this, "至少请填写一条评标专业！");
            return;
        }

        bean.setFullName(mBinding.tvName.getContent());
        bean.setUserName(mBinding.tvPhone.getContent());
        bean.setComName(mBinding.tvUnit.getContent());
        bean.setJob(mBinding.tvPost.getContent());
        bean.setAddressName(mBinding.tvAddress.getContent());
        bean.setIdentityCard(mBinding.tvSocialSecurityNumber.getContent());
        bean.setMark(mBinding.tvRemark.getEditContent());

        List<PickExpertDetailEntity.Custom> customList = mBinding.expertNew.getCustomFieldViewData();
        bean.setCustomArray(customList);
        bean.setCustomStr(JSON.toJSONString(customList));

        List<PickExpertDetailEntity.Majors> majorsList = mBinding.evaluationProfessional.getCustomFieldViewData();
        if (majors != null) {
            majorsList.add(0, majors);
        }
        bean.setMajors(majorsList);

        List<PickExpertDetailEntity.Qualifications> qualificationsList = mBinding.practisingCertificate.getCustomFieldViewData();
        bean.setQualifications(qualificationsList);

        bean.setNo(no);
        mModel.edit(this, bean);

    }

    public void setEditData(String hint) {
        MToast.showToast(this, hint);
        finish();
    }
}
